﻿using Microsoft.Data.Sqlite;
using SqlSugar;
using System.Diagnostics;

namespace DataCollection
{
    public class SqlSugarHelper
    {
        #region 属性

        static public bool DBEnable = false;

        /// <summary>错误代码
        /// 
        /// </summary>
        static public int ErrorCode = -1;

        /// <summary>
        /// 静态对象
        /// </summary>
        static private readonly Lazy<SqlSugarHelper> _lazyInstance = new Lazy<SqlSugarHelper>(() => new SqlSugarHelper());

        /// <summary>
        /// 数据库地址
        /// </summary>
        static string DBPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Collect.db");

        /// <summary>
        /// 数据库连接
        /// </summary>
        //static string ConnectionString = "Data Source=" + DBPath;

        /// <summary>
        /// 加密的数据库连接
        /// </summary>
        static string ConnectionString = new SqliteConnectionStringBuilder()
        {
            DataSource = DBPath,
            Mode = SqliteOpenMode.ReadWriteCreate,
            Password = "yb112233"
        }.ToString();

        /// <summary>
        /// DB类
        /// </summary>
        public static SqlSugarClient DB = new SqlSugarClient(new ConnectionConfig()
        {
            ConnectionString = ConnectionString,//获取加密后的字符串
            DbType = DbType.Sqlite,//数据库类型
            IsAutoCloseConnection = false,
        },
            db => {
                db.Aop.OnLogExecuting = (sql, pars) =>
                {
                    // Log.Info(sql);//输出sql,查看执行sql 性能无影响
                };
                db.Aop.OnError = (exp) =>//SQL报错
                {
                    Log.Error("SQL执行错误：【" + exp.Message + "】");
                };
        });
        #endregion

        #region 自定义方法
        private SqlSugarHelper() { }

        public static SqlSugarHelper DefaultHelper
        {
            get
            {
                return _lazyInstance.Value;
            }
        }

        static public void Setup()
        {
            SqlSugarHelper.DBEnable = SqlSugarHelper.Open();
        }

        /// <summary>
        /// 连接状态
        /// </summary>
        /// <returns></returns>
        static private bool Open()
        {
            FileInfo info = new FileInfo(DBPath);
            bool exists = info.Exists;
            if (exists == false)
            {
                return false;
            }
            else
            {
                try
                {
                    DB.Open();
                    return true;
                }
                catch (Exception ex)
                {
                    Log.Error(string.Format("数据库连接失败:{0}", ex.Message));
                    return false;
                }
            }
        }
        /// <summary>插入数据
        /// 
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static int Insertable<T>(List<T> list) where T : class, new()
        {
            try
            {
                int res = DB.Insertable(list).ExecuteCommand();
                return res;
            }
            catch (Exception ex)
            {
                Debug.WriteLine("插入记录异常：" + ex.Message);
                return ErrorCode;
            }
        }

        /// <summary>删除记录
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list"></param>
        /// <returns></returns>
        public static int Deleteable<T>(List<T> list) where T : class, new()
        {
            try
            {
                return DB.Deleteable<T>(list).ExecuteCommand();
            }
            catch (Exception ex)
            {
                Debug.WriteLine("删除记录异常：" + ex.Message);
                return ErrorCode;
            }
        }

        /// <summary>更新记录
        /// 
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static int Updateable<T>(List<T> list) where T : class, new()
        {
            try
            {
                return DB.Updateable<T>(list).ExecuteCommand();
            }
            catch (Exception ex)
            {
                Debug.WriteLine("更新记录异常：" + ex.Message);
                return ErrorCode;
            }
        }

        /// <summary>查询符合条件的记录
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="where"></param>
        /// <returns></returns>
        public static List<T> Inquireable<T>(Dictionary<string, Object>? where)
        {
            try
            {
                ISugarQueryable<T>? sugarQueryable = null;
                if (where != null)
                {
                    sugarQueryable = DB.Queryable<T>().WhereColumns(where);
                }
                else
                {
                    sugarQueryable = DB.Queryable<T>();
                }
                List<T> list = sugarQueryable.ToList();
                return list;
            }
            catch (Exception ex)
            {
                Debug.WriteLine("查询记录异常：" + ex.Message);
                return new List<T>();
            }
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="where"></param>
        /// <returns></returns>
        public static List<T> InquireableToPageList<T>(Dictionary<string, Object>? where, int pageNumber, int pageSize, ref int totalCount)
        {
            try
            {
                ISugarQueryable<T>? sugarQueryable = null;
                if (where != null)
                {
                    sugarQueryable = DB.Queryable<T>().WhereColumns(where);
                }
                else
                {
                    sugarQueryable = DB.Queryable<T>();
                }
                List<T> list = sugarQueryable.ToPageList(pageNumber, pageSize, ref totalCount);
                return list;
            }
            catch (Exception ex)
            {
                Debug.WriteLine("查询记录异常：" + ex.Message);
                return new List<T>();
            }
        }
        
        #endregion

    }
}
